/*
 * @Author: Soulmate
 * @Date: 2023-11-15 09:41:44
 * @LastEditTime: 2023-11-17 13:36:07
 * @LastEditors: Soulmate
 * @Description:
 * @FilePath: \electron-app\electron\main.ts
 * 版权声明
 */
const path = require('path');
const { app, BrowserWindow } = require('electron');
const {
  addMenuInit,
  initWindowConfigInit,
  initNotificationInit,
} = require('../electron/plugin/index.ts');
const NODE_ENV = process.env.NODE_ENV;

let win;
/**
 * @Description: electron程序入口
 * @Author: Etc.End
 * @Copyright: TigerSong
 * @CreationDate 2023-05-20 14:39:26
 */

const createWindow = () => {
  win = new BrowserWindow({
    width: 1000,
    height: 700,
    minWidth: 1000,
    minHeight: 700,
    center: true,
    skipTaskbar: false,
    // frame: true,
    // transparent: true, //创建透明窗口
    // titleBarStyle: 'hidden', //隐藏顶部任务栏,
    // titleBarOverlay: {
    //   color: '#2f3241',
    //   symbolColor: '#74b1be',
    //   height: 60,
    // }, //隐藏顶部任务栏保留右侧操作模块
    webPreferences: {
      nodeIntegration: true, //是否开启在渲染进程中node的环境
      contextIsolation: false,
      webSecurity: false,
      preload: path.join(__dirname, './preload.ts'),
    },
  });

  win.loadURL(
    NODE_ENV === 'development'
      ? 'http://localhost:5173/'
      : `file://${path.join(__dirname, '../dist/index.html')}`,
  );
  
  if (NODE_ENV === 'development') {
    /**
     * 新增electron热更新
     */
    const elePath = path.join(__dirname, '../node_modules/electron');
    require('electron-reload')('../', {
      electron: require(elePath),
    });

    win.webContents.openDevTools();

    // 打开新窗口 BrosweWindow 初始化
    // require('@electron/remote/main').initialize();
    // require('@electron/remote/main').enable(win.webContents);
  }
};

//自定义窗口菜单
addMenuInit();

// 自定义监听dom发送主进程的事件
initWindowConfigInit();

app.whenReady().then(() => {
  createWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
  });

  // 测试主线程弹窗通知
  // initNotificationInit({
  //   title: 'Electron创建通知', // 通知标题
  //   body: '创建通知成功,请对我进行描述吧', // 内容
  //   icon: path.join(__dirname, '../public/electron.png'), // 图标
  // });
});

/**
 * @Description: 限制只能打开一个页面
 * @CreationDate 2023-05-20 14:35:52
 */
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock) {
  app.quit();
} else {
  app.on('second-instance', (event, commandLine, workingDirectory) => {
    if (win) {
      if (win.isMinimized()) win.restore();
      win.focus();
    }
  });
}

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});
